package top.lshaci.learning.alibaba.cloud.seata.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.lshaci.learning.alibaba.cloud.seata.order.entity.Order;
import top.lshaci.learning.alibaba.cloud.seata.order.feign.AccountFeign;
import top.lshaci.learning.alibaba.cloud.seata.order.mapper.OrderMapper;
import top.lshaci.learning.alibaba.cloud.seata.order.service.OrderService;

/**
 * OrderServiceImpl
 *
 * @author lshaci
 * @since 1.0.0
 */
@Service
@AllArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    private final AccountFeign accountFeign;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Order create(String userId, String commodityCode, int orderCount) {
        int orderMoney = calculate(commodityCode, orderCount);

        accountFeign.debit(userId, orderMoney);

        Order order = new Order();
        order.setUserId(userId);
        order.setCommodityCode(commodityCode);
        order.setCount(orderCount);
        order.setMoney(orderMoney);
        baseMapper.insert(order);
        return order;
    }

    private int calculate(String commodityCode, int orderCount) {

        return orderCount * 100;
    }
}
